<template>
  <div class="list_dataset">
    <div style="height:100%">
      <div class="dataset_list_content">
        <!-- content -->
        <div class="list_aside"
             v-show="hideSideBar">
          <div style="padding:0 16px">
            <el-input placeholder="Search"
                      prefix-icon="el-icon-search"
                      clearable
                      @input="keyWordsChange"
                      v-model="keyWords">
            </el-input>
          </div>

          <SaveQuickFilter v-if="$refs['filter-condition'] && $refs['integration-condition'] && $refs['sort-condition']"
                           :filter="$refs['filter-condition'].filterForm"
                           :order="$refs['sort-condition'].clomu_sort"
                           type="bot"
                           :integratin="$refs['integration-condition'].integratinSelected" />

          <div class="sort_checkbox_group">
            <div class="sort_checkbox"
                 @click="selectCondit('sort')">
              <sortConditionComponent :conditionItem="conditionItem"
                                      @sortChange="listColmSort"
                                      @tabTitle="tabSelect"
                                      :options="options"
                                      ref="sort-condition"></sortConditionComponent>
            </div>
            <div class="sort_checkbox"
                 @click="selectCondit('filter')">
              <filterConditionComponent :conditionItem="conditionItem"
                                        @filterProjectForm="listColmFilter"
                                        ref="filter-condition"></filterConditionComponent>
            </div>

            <div class="sort_checkbox">
              <blockStatus :blockInfo="blockInfo"
                           @blockStatusForList="blockStatusForList"
                           @clearStatus="clearStatus"></blockStatus>
            </div>
            <div class="sort_checkbox">
              <integrationConditionComponent :integraGpHeihgt="integraGpHeihgt"
                                             @integrationGp="listColmIntegration"
                                             @setShowAllIntegrations="setShowAllIntegrations"
                                             ref="integration-condition"></integrationConditionComponent>
            </div>
          </div>
        </div>
        <div class="list_ri_content flex flex-col">
          <QuickFilter ref="quick-filter"
                       type="bot"
                       :baseOptions="quickFilterCallback()"
                       @event:add="handleAdd"
                       @event:change="handleChangeQuickFilter"
                       immediate
                       :loading.sync="quickFilterLoading"
                       v-model="selectedQuickFilter">
            <template v-slot:crumb>
              <Crumb :expand="hideSideBar"
                     @click="hideSideBar = !hideSideBar" />
            </template>
          </QuickFilter>

          <div class="flex px-16 pt-16">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-circle-plus-outline"
                       v-if="$hasPermission('sys:bots:add')"
                       @click="addOrUpdateNewBots()">{{ $t('custom.dataset.newBot') }}</el-button>

            <div class="psa_status"
                 @click="openPSASetupDialog"
                 v-if="$hasPermission('sys:bots:psastatussetting')">&nbsp;&nbsp;{{ $t('custom.bots.psaStatusSetting') }}</div>
            <div class="turn_off_all"
                 v-if="$hasPermission('sys:bots:allmessageswitch')"
                 @click="messageSwitchDialog">{{!clientSetting.value?'Turn off all':'Turn on all'}}</div>

            <!-- <NoIntegration type="bot"
                           ref="no-integration"
                           :params="{...dataForm,...filterProject}"
                           :immediate="false" /> -->

          </div>

          <div class="flex-1  h-0 py-16 pl-16"
               v-loading="dataListLoading || quickFilterLoading">

            <cardList ref="cardList"
                      :comDataList="comDataList"
                      :configScript="configScript"
                      :pageTotal="pageTotal"
                      :size="size"
                      :current="current"
                      :currListPage="dataForm.current"
                      :currListSize="dataForm.size"
                      :selectedQuickFilter="selectedQuickFilter"
                      @emitCurrPage="emitCurrPageChange"
                      @emitCurrSize="emitCurrSizeChange"
                      @deleteHandleItem="deleteHandleItem"
                      @showLinkedBotDialog="showLinkedBotDialog"
                      @showLinkedDialog="showLinkedDialog"
                      @editHandle="editHandle"
                      @cloneHandle="cloneHandle"
                      @shareHandle="shareHandle"
                      @cardQuery="cardQuery"
                      v-if="!!comDataList.length"></cardList>
            <div v-else
                 class="flex flex-col items-center justify-center h-full">

              <div class="no_data_img"></div>
            </div>

          </div>
        </div>
      </div>
    </div>

    <el-dialog :title="$t('custom.bots.all_message_switch')"
               :visible.sync="messageDialog"
               @close="canceldialog"
               width="30%">
      <div class="row">
        <div style="color:red;font-size: large;margin-bottom: 10px;">Caution:</div>
        <div style="word-break: break-word;white-space: normal;line-height: 20px;margin: 10px 10px;">
          Turning off this switch will disable all the bots' messages from being sent out to users.
          This is used for troubleshooting if you receive a large number of wrong messages.
          If you only want to turn off certain bots messages, please turn off the enable switch for each bot message.
          If you only need to turn off messages for certain users,
          please go to Settings > User Management > Action to turn off the message switch for specific users.
        </div>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   size="small"
                   @click="canceldialog()">{{ $t('cancel') }}</el-button>
        <el-button type="danger"
                   size="small"
                   @click="updateMessageSwitch()">{{ $t('custom.bots.confirm') }}</el-button>
      </span>
    </el-dialog>
    <add-or-update v-if="addOrUpdateVisible"
                   ref="addOrUpdate"
                   @refreshDataList="refreshCard"></add-or-update>
    <BotPSASeeting ref="psa-setting-component" />
    <SelectBotTemplate ref="addUpdateObj"
                       @showDataForm="jumpDataForm"></SelectBotTemplate>
    <AddUpdateBak ref="addUpdateBak"
                  @reselectTemplate="reselectTemplateFn"
                  :parentStateObj="botTem"
                  :botType="botType"
                  :isClone="isClone"
                  @refreshList="refreshCard"></AddUpdateBak>
    <ShareLinkDialog ref="share-link"
                     @refreshTagList="refreshTagList"
                     :resourceType="'Bot'"></ShareLinkDialog>
    <bot-clone :cloneVisible.sync="cloneVisible"></bot-clone>
  </div>
</template>
<script>
import Vue from 'vue'
// import { debounce } from 'lodash'
import mixinViewModule from '@/mixins/crud-view-module'
import sortConditionComponent from '@/components/viewComponents/sort-condition.vue'
import filterConditionComponent from './viewComponents/filter-condition.vue'
import blockStatus from '@/components/viewComponents/block-status.vue'
import cardList from '@/components/viewComponents/card-list.vue'
import integrationConditionComponent from '@/components/viewComponents/intergration-condition.vue'
import BotPSASeeting from './bot-psa-setting'

import { LinkComponent } from './BotFormatComponents/LinkComponent.js'
import SelectBotTemplate from './select-bot-tempalte'
import AddUpdateBak from './add-or-update-bak'
import AddOrUpdate from './bot-edit'
import botClone from './bot-clone'
import { fetchSetting, setSetting, deleteBotInfoApi } from '@/api/new'

import QuickFilter, { SaveQuickFilter, QuickFilterMixins, QuickFilterItem, Crumb } from '@/components/quick-filter'
// import { NoIntegration } from '@/components/no-integration'

export default {
  components: {
    sortConditionComponent,
    filterConditionComponent,
    integrationConditionComponent,
    cardList,
    blockStatus,
    SelectBotTemplate,
    AddUpdateBak,
    BotPSASeeting,
    AddOrUpdate,

    QuickFilter,
    SaveQuickFilter,
    // NoIntegration,
    QuickFilterItem,
    Crumb,
    botClone
  },
  mixins: [mixinViewModule, QuickFilterMixins],
  data () {
    return {
      payShow: false,
      resourceTypeId: 4,
      cloneVisible: false,
      isClone: false,
      mixinViewModuleOptions: {
        getDataListURL: '/web/bots/sys/bot/list-integration',
        getDataListURLCard: '/web/bots/sys/bot/card-list'
      },
      trueOffAll: false,
      clientSetting: {
        keyword: 'teams.message.switch',
        value: false,
        type: 'BOT_SETTING'
      },
      messageDialog: false,
      botTem: -1,
      botType: '',
      // dataForm: {
      //   internal: this.IsInternal()
      // },
      dataForm: {
        // current: 1,
        // size: 10,
        disable: true,
        scope: this.pageSource,
        showAllIntegration: false,
        internal: this.IsInternal(),
        businessType: window.location.pathname === '/Bots' ? 'Custom' : window.location.pathname === '/CrossTenantBots' ? 'MSPbots Internal' : 'Template'
      },
      groupOptions: { columns: ['integration'] },
      pageSettings: { pageSize: 100, pageSizes: [50, 100, 200, 1000], pageCount: 4 },
      loading: false,
      sortSettings: {
        columns: [
          { field: 'name', direction: 'Ascending' }
        ]
      },
      linkBotVisible: false,
      Datasetshow: false,
      viewValue: 'List',
      viewValueList: [{ label: 'Grid', value: 'Grid', icon: 'cuifont icon_table' }, { label: 'List', value: 'List', icon: 'cuifont icon_list' }],
      options: [
        {
          value: 'name',
          label: 'Name'
        },
        {
          value: 'business_type',
          label: 'Type'
        },
        {
          value: 'status',
          label: 'Status'
        },
        {
          value: 'create_date',
          label: 'Created Date'
        },
        {
          value: 'creatorName',
          label: 'Creator'
        },
        {
          value: 'update_date',
          label: 'Last Modified'
        },
        {
          value: 'updateByName',
          label: 'Updater'
        },
        {
          value: 'ready',
          label: 'Ready'
        },
        {
          value: 'received',
          label: 'Received'
        },
        {
          value: 'read',
          label: 'Read'
        }

      ],
      keyWords: '',
      // keyWordsValue: '',

      conditionItem: '',
      hideSideBar: true,
      configScript: {
        id: 'id',
        name: 'name',
        status: 'status',
        description: 'description',
        businessType: 'businessType',
        icon: 'integrationIcon',
        botNum: 'botNum',
        modelNum: 'modelNum',
        integration: 'integration',
        createDate: 'createTime',
        creatorName: 'creatorName',
        updateDate: 'updateTime',
        updateByName: 'updateByName',
        lastSyncDate: 'lastSyncDate',
        ownerName: 'ownerName',
        Permission: 'bots',
        read: 'read',
        ready: 'ready',
        received: 'received',
        enable: 'enable',
        alert: 'alert',
        escalation: 'escalation',
        tagList: 'tagList'
      },
      filterProject: {
        'order': [
          { 'field': 'name', 'sort': 'ASC' }
        ],
        'filter': {
          'type': [],
          'status': [],
          'createDate': {
            'from': '',
            'to': ''
          },
          'updateDate': {
            'from': '',
            'to': ''
          },
          'creator': [],
          'updateBy': [],
          'ready': {
            min: undefined,
            max: undefined
          },
          'received': {
            min: undefined,
            max: undefined
          },
          'read': {
            min: undefined,
            max: undefined
          }
        },
        'integrationGroup': [],
        blockStatus: {
          enable: null,
          alert: null,
          escalation: null
        }
      },
      blockInfo: [
        {
          text: 'Trigger',
          value: false
        },
        {
          text: 'Alert',
          value: false
        },
        {
          text: 'Escalate',
          value: false
        }
      ],
      integraGpHeihgt: 0,
      source: null,
      selectedQuickFilter: {
        id: 'bot-all'
      },

      quickFilterLoading: false,

      botNumber: {},
      botNumberLoading: false
    }
  },
  watch: {
    selectedQuickFilter: {
      handler: function (value) {
        if (window.location.pathname === '/CrossTenantBots') {
          this.dataForm.businessType = 'MSPbots Internal'
        } else {
          if (value.id === 'bot-Template') {
            this.dataForm.businessType = 'Template'
          } else if (value.id === 'bot-all') {
            this.dataForm.businessType = 'Custom'
          } else if (value.id === 'my-Favorites') {
            this.dataForm.businessType = 'Custom,Template'
          } else {
            // this.dataForm.businessType = window.location.pathname === '/Bots' ? 'Custom' : window.location.pathname === '/InternalBots' ? 'MSPbots Internal' : 'Template'
          }
        }
      },
      immediate: true
    }
  },
  computed: {
    comDataList () {
      var retdata = []
      retdata = this.dataList
      return retdata
    }
  },
  created () {
    this.init()
    this.lisonPathEmit()
    LinkComponent.$on('changeSwitchHanderForList', () => {
      this.getDataList()
    })
    LinkComponent.$on('initPageList', () => {
      this.refreshCard()
    })
  },
  destroyed () {
    LinkComponent.$off('changeSwitchHanderForList')
    LinkComponent.$off('initPageList')
  },

  mounted () {
    this.tabSelect({ tab: false, text: 'sort' })
    // if (this.$refs['no-integration']) {
    //   this.$refs['no-integration'].refresh()
    // }
  },
  methods: {
    refreshCard () {
      this.refreshQuickFilter()
      this.cardQuery()
    },
    cloneHandle (row) {
      // this.cloneVisible = true
      this.isClone = true
      this.$nextTick(() => {
        this.$store.commit('BOTFORMEDIT', true)
        this.$refs.addUpdateBak.dataForm.id = row.id
        this.$refs.addUpdateBak.init()
      })
    },
    quickFilterCallback () {
      const basicOptions = [
        {
          id: 'my-Favorites',
          name: this.$t('custom.widget.myFavorites'),
          filterJson: {
            filter: {
              type: []
            }
          },
          close: false
        },
        {
          id: `bot-all`,
          name: this.$t('custom.reports.myBot'),
          filterJson: {
            filter: {
              type: []
            }
          },
          close: false
        },
        {
          id: `bot-Template`,
          name: this.$t('custom.sys.botsTemplate'),
          filterJson: {
            filter: {
              type: []
            }
          },
          close: false
        }
      ]

      return [...basicOptions]
    },
    lisonPathEmit () {
      LinkComponent.$on('botViewShowEdit', (data) => {
        this.addOrUpdateHandle(data)
      })
    },
    tabSelect (val) {
      let height = document.querySelector('.dataset_list_content').offsetHeight
      if (val.text === 'sort' && val.tab) {
        this.integraGpHeihgt = height - 10 - 121 - 60 - 80 - 170
      }
      if (val.text === 'sort' && !val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 60 - 80 - 170
      }
    },
    // keyWordsChange: debounce(function (val) {
    //   this.keyWordsValue = val
    //   if (this.$refs.cardList) this.$refs.cardList.scrollTop()
    // }, 1000),
    listColmSort (val) {
      this.filterProject.order = val
      if (window.CardListSource) window.CardListSource()

      this.cardQuery()
    },
    listColmFilter (val) {
      this.filterProject.filter = val
      if (window.CardListSource) window.CardListSource()

      this.cardQuery(null, 1)
    },
    listColmIntegration (val) {
      this.filterProject.integrationGroup = val
      if (window.CardListSource) window.CardListSource()

      this.cardQuery(null, 1)
    },
    loadComDataList () {
      this.pageSize += 10
    },
    selectCondit (val) {
      this.conditionItem = val
    },
    jumpNewDatasetPage (row) {
      this.commandClick('View', row)
    },
    emitCurrPageChange (page) {
      this.dataForm.current = page
      this.cardQuery()
    },
    emitCurrSizeChange (size) {
      this.dataForm.size = size
      this.cardQuery()
    },
    editHandle (row) {
      // if (!this.$hasPermission('sys:dataset:edit') || !this.$hasPermissionRouterName(('dataset-' + row.name).replace(/ /g, ''))) {
      //   return this.$message.error(this.$t('prompt.nopermission'))
      // }
      // this.addOrUpdateHandle(row.id)
      this.isClone = false
      this.$nextTick(() => {
        this.$store.commit('BOTFORMEDIT', true)
        this.$refs.addUpdateBak.dataForm.id = row.id
        this.$refs.addUpdateBak.init()
      })
    },
    deleteHandleItem (row) {
      // if (!this.$hasPermission('sys:dataset:delete') || !this.$hasPermissionRouterName(('dataset-' + row.name).replace(/ /g, ''))) {
      //   return this.$message.error(this.$t('prompt.nopermission'))
      // }
      // if (row.modelNum !== 0) {
      //   this.showLinkedDialog(row.id)
      // } else {
      //   this.deleteHandle(row.id)
      // }
      this.deleteBots(row.id, row)
    },
    showLinkedDialog (id) {
      this.linkWidgetVisible = true
      this.$nextTick(() => {
        this.$refs['linkWidget'].dataForm.id = id
        this.$refs['linkWidget'].init()
      })
    },
    showLinkedBotDialog (id) {
      this.linkBotVisible = true
      this.$nextTick(() => {
        this.$refs['linkBot'].dataForm.dataSourceId = id
        this.$refs['linkBot'].init()
      })
    },
    showDataset (data) {
      this.$router.push({ path: `dataset-${data.id}`, query: { pageid: `${data.id}` } })
    },
    formatDataList () {
      // this.dataList
      let tempList = []
      this.dataList.map(e => {
        if (e.configStatus && e.configStatus.status === 1) {
          tempList.push(e)
        }
      })
      return tempList
    },
    IsInternal () {
      let path = window.location.pathname
      if (path === '/CrossTenantBots') {
        return true
      } else {
        return false
      }
    },
    addOrUpdateNewBots (id) {
      this.$nextTick(() => {
        this.$refs.addUpdateObj.dataForm.id = id
        this.$refs.addUpdateObj.init()
      })
    },
    jumpDataForm (item) {
      this.$nextTick(() => {
        this.$refs.addUpdateBak.init()
      })
      this.botTem = item.item
      this.botType = item.type
    },
    reselectTemplateFn () {
      this.$nextTick(() => {
        this.$refs.addUpdateBak.visible = false
        this.$refs.addUpdateObj.visible = true
      })
    },
    init () {
      // if (localStorage.getItem('botview') === 'List')
      this.getMessageSwitch()
    },
    setShowAllIntegrations (val) {
      this.dataForm.showAllIntegration = val

      if (window.CardListSource) window.CardListSource()
      this.dataListLoading = true

      this.cardQuery(null, 1)
    },
    blockStatusForList (val) {
      if (window.CardListSource) window.CardListSource()
      this.filterProject.blockStatus.enable = val[0].value ? val[0].value : null
      this.filterProject.blockStatus.alert = val[1].value ? val[1].value : null
      this.filterProject.blockStatus.escalation = val[2].value ? val[2].value : null
      this.cardQuery(null, 1)
    },
    clearStatus () {
      this.blockInfo = [
        {
          text: 'Trigger',
          value: false
        },
        {
          text: 'Alert',
          value: false
        },
        {
          text: 'Escalate',
          value: false
        }
      ]
      this.filterProject.blockStatus.enable = this.blockInfo[0].value ? this.blockInfo[0].value : null
      this.filterProject.blockStatus.alert = this.blockInfo[1].value ? this.blockInfo[1].value : null
      this.filterProject.blockStatus.escalation = this.blockInfo[2].value ? this.blockInfo[2].value : null
      this.cardQuery(null, 1)
    },
    messageSwitchDialog () {
      // this.trueOffAll = !this.trueOffAll
      if (!this.clientSetting.value) {
        this.messageDialog = true
      } else {
        this.updateMessageSwitch()
      }
    },
    canceldialog () {
      this.messageDialog = false
      this.getMessageSwitch()
    },
    getMessageSwitch () {
      Vue['_this_my_bot_'] = this
      const params = {
        keyword: 'teams.message.switch'
      }
      fetchSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          let tempData = res.data
          if (tempData.value === 'false') {
            tempData.value = true
          } else {
            tempData.value = false
          }
          this.clientSetting = tempData
        }
      })
    },
    updateMessageSwitch () {
      if (!this.$store.state.user.email) {
        return this.$message.error(this.$t('custom.bots.updateBotsMessage'))
      }
      const params = {
        ...this.clientSetting,
        value: !this.clientSetting.value ? 'false' : 'true',
        email: this.$store.state.user.email
      }
      setSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.messageDialog = false
        this.trueOffAll = true
        this.getMessageSwitch()
        return this.$message.success(res.msg)
      }).catch(() => {

      })
    },
    openPSASetupDialog () {
      this.$refs['psa-setting-component'].openDialog()
    },
    deleteBots (id, row) {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const params = {
          id: id
        }
        deleteBotInfoApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (row.originalId && row.type === 100101) {
            this.deleteShareToCommunity(row, 'bot')
          }
          this.$refs['quick-filter'].getQuickFilters('integration')
          this.cardQuery()
          return this.$message.success(res.msg)
        })
      }).catch(() => {
      })
    },
    refreshTagList () {
      this.$refs['quick-filter'].getQuickFilters('integration')
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.meta.name === from.meta.name) {
      if (this.$store.state.contentTabs.findIndex(item => item.name === to.name) > -1) {
        this.$set(
          this.$store.state.contentTabs,
          this.$store.state.contentTabs.findIndex(item => item.name === to.name),
          { ...this.$store.state.contentTabs[this.$store.state.contentTabs.findIndex(item => item.name === to.name)], title: to.meta.title }
        )
      }
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.continue-rule-form {
  padding: 20px 0;
  &--text {
    font-size: 18px;
    color: #404040;
    line-height: 26px;
    text-align: center;
    padding: 38px 0 15px;
  }
  &--tip {
    font-size: 14px;
    color: #808080;
    line-height: 20px;
    text-align: center;
    margin-bottom: 40px;
  }
}
.psa_status {
  width: 115px;
  height: 32px;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.75);
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  margin-left: 10px;
}
.turn_off_all {
  width: 109px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  font-weight: 400;
  color: #404040;
  line-height: 32px;
  margin-left: 10px;
  text-align: right;
  padding-right: 8px;
  cursor: pointer;
  background-image: url("#{$--ossLink}/app/view_pageheader/Turnonall.png");
  background-size: 14px;
  background-position: 8px center;
  background-repeat: no-repeat;
}
.list_dataset {
  height: 100%;
  .dataset_list_content {
    height: 100%;
    background-color: #fff;
    margin-top: 10px;
    border-radius: 4px;
    height: calc(100% - 60px);

    .list_aside {
      display: flex;
      flex-direction: column;
      height: 100%;
      width: 283px;
      float: left;
      padding: 16px 0px;
      box-shadow: 1px 0px 0px 0px #f0f0f0;
      overflow: hidden;
      transition: 1s width;
      .sort_checkbox_group {
        overflow-y: auto;
        // max-height: 620px;
        flex: 1;
      }
    }
    .list_ri_content {
      transition: 1s width;
      height: 100%;

      .no_data_img {
        width: 164px;
        height: 99px;
        margin-bottom: 5px;
        background-image: url("#{$--ossLink}/app/view_pageheader/dataset_nodate.png");
        background-repeat: no-repeat;
        background-size: 164px 99px;
        background-position: center;
      }
      .no_data_text {
        margin-bottom: 10px;
        height: 20px;
        font-size: 14px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.5);
        line-height: 20px;
      }
      .no_data_intro {
        width: 200px;
        height: 34px;
        font-size: 12px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.25);
        line-height: 17px;
        text-align: center;
        margin-bottom: 10px;
      }
      .widget-library--text {
        color: #17b3a3;
        text-decoration: underline;
      }
    }
  }
}
</style>
